<script lang="ts" setup>
import { type FileItem, useFileStore } from "@store/useFileStore"

const fileStore = useFileStore()
const { uploadList } = toRefs(fileStore)
const { deleteFile, uploadFile } = fileStore
const haveImg = computed(() => uploadList.value.length > 0)

const targetFile = ref<FileItem | undefined>(undefined)
const clickEsc = (e: KeyboardEvent) => {
  if (e.code === "Escape") hideDetail()
}

const showDeatil = (v: FileItem) => {
  targetFile.value = v
  // html dom 设置为不滚动
  document.documentElement.classList.add("show-detail")
  // 添加监听 ESC 事件
  document.body.addEventListener("keydown", clickEsc)
}
const hideDetail = () => {
  targetFile.value = undefined
  document.documentElement.classList.remove("show-detail")
  // 移除监听 ESC 事件
  document.body.removeEventListener("keydown", clickEsc)
}
</script>

<template>
  <div class="list-box" v-if="haveImg">
    <div class="img-item" v-for="(v, i) in uploadList" :key="v.name">
      <svg @click="deleteFile(i)" class="cancel" t="1664521886427" viewBox="0 0 1024 1024" version="1.1"
        xmlns="http://www.w3.org/2000/svg" p-id="1052" width="200" height="200">
        <path
          d="M512 64C264.8 64 64 264.8 64 512s200.8 448 448 448 448-200.8 448-448S759.2 64 512 64z m238.4 641.6l-45.6 45.6L512 557.6 318.4 750.4l-45.6-45.6L467.2 512 273.6 318.4l45.6-45.6L512 467.2l193.6-193.6 45.6 45.6L557.6 512l192.8 193.6z"
          p-id="1053"></path>
      </svg>
      <img @click="showDeatil(v)" class="show" :src="v.base64" alt="img load error" draggable="false">
    </div>
  </div>
  <div class="upload-btn" v-if="haveImg" @click="uploadFile">{{$t("list.btn")}}</div>
  <ImageDeatil :file="targetFile" @hideDetail="hideDetail" />
</template>

<style lang="scss">
@media screen and (max-width: 420px) {
  .list-box {
    .img-item {
      .show {
        width: 120px !important;
        height: 120px !important;
        object-fit: cover;
      }
    }
  }
}

.list-box {
  padding: 20px 14px;
  @include center;

  .img-item {
    position: relative;
    cursor: pointer;
    margin: 28px 14px 0;

    .show {
      width: 150px;
      height: 150px;
      object-fit: cover;
    }

    .cancel {
      position: absolute;
      top: -8px;
      left: -8px;
      width: 25px;
      height: 25px;
      fill: #515151;
    }

    .cancel:hover {
      fill: $uploadColor;
    }
  }
}

.upload-btn {
  margin: 24px auto;
  text-align: center;
  cursor: pointer;
  width: 172px;
  height: 58px;
  font-size: 18px;
  line-height: 58px;
  font-weight: 600;
  border-radius: 29px;
  color: $uploadFontColor;
  border: 1px solid $uploadColor;
}

.upload-btn:hover {
  background-color: $uploadColor;
  border: unset;
}
</style>
